<?php

namespace App\Http\Controllers\Admin;

use App\Models\Goods;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Excel;
use TijsVerkoyen\CssToInlineStyles\Exception;

class GoodsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $goods = Goods::orderBy('id','DESC')->paginate();
        return view('goods.index',compact('goods'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        Goods::destroy($id);
        return redirect()->route('admin.goods.index')->with('success','Goods delete successfully');
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function createExcel()
    {
        //
        return view('goods.excel_create');
    }

    /**
     * @param Request $request
     */
    public function storeExcel(Request $request)
    {
        //
        $file = $request->file('goods');

        if(!$file->isValid()){
            return $file->getError();
        }
        $realPath = $file->getRealPath(); //临时地址

        ini_set('memory_limit','128M');//增加内存
        $res = [];
        Excel::load($realPath, function($reader) use( &$res ) {
            $data = $reader->all();
            $res = $reader->toArray();
        });

        Goods::insert($res[0]);
        return redirect()->route('admin.goods.index')->with('success','Goods created successfully');
    }


}
